package com.tqfframe.studydemo.myDubboRpc.core.porxy;

import com.alibaba.fastjson.JSONObject;
import com.tqfframe.studydemo.myDubboRpc.core.entiy.PorxyEntity;
import com.tqfframe.studydemo.myDubboRpc.core.handler.ClinetHandler;
import com.tqfframe.studydemo.myDubboRpc.core.util.TypeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by Tang-QiFeng on 2022/2/18
 */
public class ClinetPorxy implements InvocationHandler {

    private Logger logger=LoggerFactory.getLogger(this.getClass());

    //需要代理对象
    private Class aClass;
    private ClinetHandler client;

    public ClinetPorxy(Class aClass,ClinetHandler client) {
        this.aClass = aClass;
        this.client = client;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        PorxyEntity porxyEntity=new PorxyEntity();
        //告诉服务端调用的是哪个类
        porxyEntity.setName(aClass.getName());
        //告诉服务端调用的是哪个方法
        porxyEntity.setMethod(method.getName());
        //告诉服务端调用方法传入的参数
        porxyEntity.setArgs(args);
        //告诉服务端调用方法的参数类型
        porxyEntity.setParameterTypes(method.getParameterTypes());
        String jsonStr = JSONObject.toJSONString(porxyEntity);
        client.setPara(jsonStr);
        Object result=client.call();
        if(!method.getReturnType().equals("void")){
            //根据返回的结果进行格式转换
            return TypeUtil.typeChange(method.getReturnType().getName(),result.toString());
        }

        return result;
    }

    // 生成代理类
    public Object creatProxyedObj() {
        return Proxy.newProxyInstance(aClass.getClassLoader(),
                new Class[]{aClass}, this);
    }



}
